//
//  InputCodeView.swift
//  casdon_swiftUI
//
//  Created by ww on 2025/4/20.
//
import SwiftUI
import FlowStacks

struct VerificationCodeView: View {
    @StateObject private var viewModel: VerificationCodeViewModel
    let numberOfFields = 6
    @FocusState private var focusedField: Int?  // FocusState用于管理焦点
    @EnvironmentObject var navigator: FlowNavigator<LoginStack>
    init(viewModel: VerificationCodeViewModel) {
        _viewModel = StateObject(wrappedValue: viewModel)
    }
    
    var body: some View {
        VStack {
            NavigationBar(title: "")
            HStack{
                Text("输入验证码")
                    .font(.system(size: 24))
                    .foregroundColor(AppColors.Gy1)
                    .bold()
                Spacer()
            }.padding(.leading, 24)
            .padding(.top, 20)
            
            HStack(spacing: 12) {
                ForEach(0..<numberOfFields, id: \.self) { index in
                    VerificationTextField(
                        index: index,
                        text: $viewModel.code[index],
                        focusedField: $focusedField
                    )
                    .frame(width: 40, height: 50)
                    .textFieldStyle(PlainTextFieldStyle())
                    .multilineTextAlignment(.center)
                    .keyboardType(.numberPad)
                    .overlay(
                        Rectangle()
                            .frame(height: 1)
                            .foregroundColor(AppColors.Gray5)
                            .padding(.top, 30)
                    )
                }
            }
            .padding(.top, 74)
            
            // 显示手机号码
            HStack {
                Text("已发送至 \(viewModel.account!)")
                    .font(.system(size: 14))
                    .foregroundColor(AppColors.Gray5)

                Button(action: {
                    viewModel.timeOutStart()
                }) {
                    Text(viewModel.remainingSeconds > 0
                         ? "重新发送 \(viewModel.remainingSeconds)s"
                         : "重新发送")
                }
                .disabled(viewModel.remainingSeconds > 0)
                .font(.system(size: 14))
                .foregroundColor(viewModel.remainingSeconds > 0 ? AppColors.Gray5 : AppColors.Brand3)
                Spacer()
            }
            .padding(.leading, 24)
            .padding(.top, 8)

            Spacer()
        }
        .padding()
        .onChange(of: viewModel.verifyCodeSuccess) { newValue in
            if newValue {
                   navigator.push(.setPwd(account: viewModel.account!, isRegister: viewModel.verifyType == .register ? true : false))
                  
            }
        }
        
        .toast(isPresented: $viewModel.showToast, message: viewModel.toastMsg)
    }
}

struct VerificationTextField: View {
    var index: Int
    @Binding var text: String
    @FocusState.Binding var focusedField: Int? // 这里使用 FocusState.Binding 绑定
    @State private var tempText: String = ""

    var body: some View {
        TextField("", text: $tempText)
            .focused($focusedField, equals: index)
            .font(.system(size: 24))
            .frame(maxWidth: .infinity)
            .keyboardType(.numberPad)
            .onChange(of: tempText) { newValue in
                if newValue.isEmpty {
                    // 处理删除操作
                    text = ""
                    // 如果不是第一个输入框，跳转到前一个输入框
                    if index > 0 {
                        focusedField = index - 1
                    }
                    return
                }
                
                // 只允许输入一个数字
                if let firstChar = newValue.first, firstChar.isNumber {
                    text = String(firstChar)
                    tempText = String(firstChar)
                    
                    // 如果不是最后一个输入框，自动跳到下一个
                    if index < 5 {
                        focusedField = index + 1
                    }
                } else {
                    // 如果输入的不是数字，恢复之前的值
                    tempText = text
                }
            }
            .onAppear {
                tempText = text
                if index == 0 {
                    focusedField = index
                }
            }
    }
}
